﻿#if NEW_INPUT_SYSTEM
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;

namespace GameToolkit
{
    [DisallowMultipleComponent]
    public class PCBaseInput : BaseInput
    {
        Mouse mMouse;
        ButtonControl[] mMouseBtns;
        bool[] mWasPressed;

        protected override void OnEnable()
        {
            base.OnEnable();
            mMouse = InputSystem.GetDevice<Mouse>();
            mMouseBtns = new ButtonControl[3];
            mWasPressed = new bool[3];
            if (mMouse != null)
            {
                mMouseBtns[0] = mMouse.leftButton;
                mMouseBtns[1] = mMouse.rightButton;
                mMouseBtns[2] = mMouse.middleButton;
            }
        }

        public override bool touchSupported => false;

        public override bool mousePresent => mMouse != null;

        public override Vector2 mousePosition
        {
            get
            {
                return mMouse == null ? Vector2.zero : mMouse.position.value;
            }
        }

        public override Vector2 mouseScrollDelta
        {
            get
            {
                return mMouse.scroll.value;
            }    
        }

        public override bool GetMouseButtonDown(int button)
        {
            if (button < mMouseBtns.Length)
            {
                var pressed = mMouseBtns[button] != null && mMouseBtns[button].isPressed;
                return pressed && !mWasPressed[button];
            }
            else
            {
                return false;
            }
        }

        public override bool GetMouseButton(int button)
        {
            var btn = button < mMouseBtns.Length ? mMouseBtns[button] : null;
            return btn != null && btn.isPressed;
        }

        public override bool GetMouseButtonUp(int button)
        {
            if (button < mMouseBtns.Length)
            {
                var pressed = mMouseBtns[button] != null && mMouseBtns[button].isPressed;
                return !pressed && mWasPressed[button];
            }
            else
            {
                return false;
            }
        }

        private void LateUpdate()
        {
            for (int i = 0; i < mMouseBtns.Length; i++)
            {
                mWasPressed[i] = mMouseBtns[i] != null && mMouseBtns[i].isPressed;
            }
        }
    }
}

#endif